package org.java.user.controller;

import org.java.commons.vo.Result;
import org.java.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/destroy")
public class DestroyAccountController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String destroy(){
        return "destroy";
    }

    @PostMapping
    public ModelAndView destroy( @AuthenticationPrincipal OAuth2Authentication authentication,
                                 @RequestParam("password") String password){
        Result result = this.destroyJson(authentication, password);
        ModelAndView mav = new ModelAndView();
        if (result.getCode() == 1) {
            // 销户成功
            mav.setViewName("redirect:/logout");
        } else {
            // 销户失败
            mav.setViewName("destroy");
        }
        mav.addObject("result", result);
        return mav;
    }

    @PostMapping(produces = "application/json")
    private Result destroyJson(@AuthenticationPrincipal OAuth2Authentication authentication,
                               @RequestParam("password") String password) {
        String id = authentication.getName();
        return this.userService.destroy(id, password);
    }

}
